import os.path

import profile
import tkinter.simpledialog
import helpers.FileHelper as FileHelper
import helpers.MiscHelper as MiscHelper
import helpers.MathHelper as MathHelper
import helpers.GUIHelper as GUIHelper
import package.PackageManager as PackageManager
import PIL.Image as Image


def cmd_rename(opts, args):
    if len(args) < 1:
        return
    paths = GUIHelper.ask_files()
    paths = list(paths)
    paths.sort()

    fmt = args[0]
    exp = 4 if len(paths) > 1000 else 3
    for i, src in enumerate(paths):
        name, base = FileHelper.split(src)
        name = fmt.format(str(i).zfill(exp))
        dst = FileHelper.solve_path(base, name)
        FileHelper.mv(src, dst)


def normalize_size(w, h, m):
    r = MathHelper.gcd(w, h)
    w //= r
    h //= r
    r = min(m // w, m // h)
    w *= r
    h *= r
    return w, h


def force_resize(w, h, m):
    if w > h:
        s = m / w
        w = m
        h = round(h * s)
    else:
        s = m / h
        h = m
        w = round(w * s)
    return w, h


def cmd_normalize_images(opts, args):
    if len(args) < 1:
        return
    limit = int(args[0])
    files = GUIHelper.ask_files()
    for filepath in files:
        img = Image.open(filepath)
        rw, rh = img.size
        if rw > limit or rh > limit:
            nw, nh = normalize_size(rw, rh, limit)
            if nw == 0 or nh == 0:
                nw, nh = force_resize(rw, rh, limit)
            print("resizing... '{}': {}:{} => {}:{}".format(os.path.basename(filepath), rw, rh, nw, nh))
            img.resize((nw, nh)).save(filepath)
